package com.bootdo.blog.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.blog.domain.ContentDO;
import com.bootdo.blog.service.ContentService;
import com.bootdo.blog.service.WechatService;
import com.bootdo.common.config.Constant;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.system.domain.BpostionDO;
import com.bootdo.system.service.BpostionService;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.*;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.kit.SignatureCheckKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.impl.util.CollectionUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;


/**
 *
 *
 * @author bootdo 1992lcg@163.com
 */
@RequestMapping("/weChatApi")
@Controller
@Api(description = "微信api", position = 1)
public class WeChatController extends ApiController {

@Autowired
private WechatService wechatService;
@Autowired
private BpostionService bpostionService;

	@GetMapping()
	String weChatApi() {
		return "weChatApi/index/main";
	}
	private static String appId="wx24dffff92fcc6bad";
	private static String secret="dd19890387d1beb557ff9322c22d6b1f";
	private static String redirect_uri="http://www.51canting.com/call";



	@GetMapping("/open/verifyToken")
	@ApiOperation(value = "验证token")
	@ResponseBody
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		getApiConfig();
		// 确认请求来至微信
		if (SignatureCheckKit.me.checkSignature(signature,timestamp,nonce)) {
			response.getWriter().print(echostr);
		}else{
			System.out.println("失败");
		}
	}




	@GetMapping("/open/authorizeURL")
	@ApiOperation(value = "获取网页授权url")
	@ResponseBody
	public R authorizeURL() {
		ApiConfig apiConfig = getApiConfig();
		String authorizeURL = SnsAccessTokenApi.getAuthorizeURL(apiConfig.getAppId(), redirect_uri, false);

		if(authorizeURL!=null){
			return R.ok("授权成功").put("authorizeURL",authorizeURL);
		}else {
			return R.error("授权失败");
		}


	}




	@GetMapping("/open/accessToken/{code}")
	@ApiOperation(value = "根据code获取accessToken")
	@ResponseBody
	public R getSnsAccessToken(@PathVariable String code) {
		ApiConfig apiConfig = getApiConfig();
		SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(apiConfig.getAppId(), secret, code);
		wechatService.getUserInfoAndSave(snsAccessToken.getAccessToken(),snsAccessToken.getOpenid());

		Map<String, Object> paras= new HashMap<>();
		paras.put("openApi",snsAccessToken.getOpenid());
		List<BpostionDO> list = bpostionService.list(paras);

		if(snsAccessToken!=null){
			return R.ok("授权成功").put("snsAccessToken",snsAccessToken).put("recommendList",list);
		}else {
			return R.error("授权失败");
		}


	}

	@GetMapping("/open/recommendList/{openId}")
	@ApiOperation(value = "根据openId获取推荐信息")
	@ResponseBody
	public R recommendList(@PathVariable String openId) {
		Map<String, Object> paras= new HashMap<>();
		paras.put("openApi",openId);
		List<BpostionDO> list = bpostionService.list(paras);
        return R.ok("查询成功").put("recommendList",list==null?new ArrayList<>():list);
	}




	//分享
	@GetMapping("/open/JsTicketApi")
	@ApiOperation(value = "jsapi_ticket是公众号用于调用微信JS接口的临时凭证，分享接口")
	@ResponseBody
	public R getJsTicketApi(@RequestParam String url)throws UnsupportedEncodingException  {
		ApiConfig apiConfig = getApiConfig();
		JsTicket ticket = JsTicketApi.getTicket(JsTicketApi.JsApiType.jsapi);


		String timeStamp = Long.toString(System.currentTimeMillis() / 1000);
		String nonceStr = Long.toString(System.currentTimeMillis());
		Map<String, String> packageParams = new HashMap<String, String>();

		packageParams.put("noncestr", nonceStr);
		packageParams.put("timestamp", timeStamp);
		packageParams.put("jsapi_ticket", ticket.getTicket());
		packageParams.put("url", URLDecoder.decode(url, "UTF-8"));


		String packageSign = PaymentKit.packageSign(packageParams,false);

		String signature = DigestUtils.shaHex(packageSign);

		packageParams.put("signature", signature);
		packageParams.put("appid", apiConfig.getAppId());


		if(Optional.ofNullable(ticket).isPresent()){
			return R.ok("授权成功").put("data",packageParams);
		}else {
			return R.error("授权失败");
		}
	}



	@Override
	public ApiConfig getApiConfig() {
		ApiConfig apiConfig =new ApiConfig();
		apiConfig.setAppId("wx24dffff92fcc6bad");
		apiConfig.setAppSecret("dd19890387d1beb557ff9322c22d6b1f");
		apiConfig.setToken("verify_token");
		apiConfig.setEncodingAesKey("ozMYIVWlRF6IQKtlnDiSWoJt0LM6OqahlQpbEqCo2kO");
		ApiConfigKit.setThreadLocalApiConfig(apiConfig);
		return ApiConfigKit.getApiConfig();
	}






}
